package com.tomdd.router;

import com.tomdd.handler.MessageHandler;
import com.tomdd.message.WxMessage;
import com.tomdd.message.WxOutMessage;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 消息路由规则
 *
 * @author zx
 * @date 2025-03-12 13:46
 */

public class WxMpMessageRouterRule {
    private final WxMpMessageRouter routerBuilder;
    private List<MessageHandler> handlers = new ArrayList<>();
    private String msgType;

    public String getMsgType() {
        return msgType;
    }

    public void setMsgType(String msgType) {
        this.msgType = msgType;
    }

    public WxMpMessageRouterRule msgType(String msgType) {
        this.msgType = msgType;
        return this;
    }

    public WxMpMessageRouterRule(WxMpMessageRouter routerBuilder) {
        this.routerBuilder = routerBuilder;
    }

    /**
     * 设置微信消息处理器
     *
     * @param handler the handler
     * @return the wx mp message router rule
     */
    public WxMpMessageRouterRule handler(MessageHandler handler) {
        return handler(handler, (MessageHandler) null);
    }

    public WxMpMessageRouterRule handler(MessageHandler handler, MessageHandler... otherHandlers) {
        this.handlers.add(handler);
        if (otherHandlers != null) {
            for (MessageHandler otherHandler : otherHandlers) {
                this.handlers.add(otherHandler);
            }
        }
        return this;
    }

    /**
     * 规则结束,代表如果一个消息匹配改规则,那么他将不会在进入其他规则。
     *
     * @return the wx mp message router
     */
    public WxMpMessageRouter end() {
        this.routerBuilder.getRules().add(this);
        return this.routerBuilder;
    }


    /**
     * 处理微信推送过来的消息
     *
     * @param message 消息
     * @param context 上下文携带的参数
     * @return 响应消息
     */
    public WxOutMessage service(WxMessage message, Map<String, Object> context) {
        WxOutMessage outMessage = null;
        for (MessageHandler handler : handlers) {
            if (handler == null) {
                continue;
            }
            outMessage = handler.handler(message, context);
        }
        return outMessage;
    }

    public WxMpMessageRouter getRouterBuilder() {
        return routerBuilder;
    }

    protected boolean test(WxMessage wxMessage) {
        return this.msgType.equals(wxMessage.getMsgType());
    }

}
